package com.csdj.t301.controller;

import com.alibaba.fastjson.JSON;
import com.csdj.t301.aop.Role;
import com.csdj.t301.entity.User;
import com.csdj.t301.service.UserService;
import com.csdj.t301.vo.WebResult;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;


/**
 * author:cloud
 * date:2021/3/11 0011
 **/
@Controller//交给spring管理
@RequestMapping("/user")//springmvc 会将这个类当成一个控制器
public class UserController {

    private Logger log = Logger.getLogger("user");

    @Resource
    private UserService userService;

    @GetMapping("/total")//springmvc 会把这个方法当成控制器来管理
    public ModelAndView userTotal(){
        int count = userService.getUserCount();
        ModelAndView mav = new ModelAndView("user");
        mav.addObject("count",count);
        log.info(" user count is "+count);
        return mav;
    }

    @PostMapping("/update")
    public String update(@Validated User user, BindingResult bindingResult){
        if(bindingResult.hasErrors()){
            return "update";
        }
        if(userService.update(user)){
            return "success";
        }
        return "success";
    }

    @GetMapping("/update/{id}")
    public ModelAndView getUpdateView(@PathVariable int id){
        User user = userService.getUser(id);
        if(user != null){
            ModelAndView mav = new ModelAndView("update");
            mav.addObject("user",user);
            return mav;
        }else{
            ModelAndView mav = new ModelAndView("update");
            mav.addObject("error","用户不存在");
            return mav;
        }
    }

    @Role({"normal","admin","other"})
    @GetMapping(value = "/user/{id}")
    @ResponseBody
    public WebResult getUserJson(@PathVariable int id){
        User user = userService.getUser(id);
        WebResult result =  new WebResult(200,user);
        result.putData("total",23)
                .putData("name","t301");
        return result;
    }

    @GetMapping("/str/{id}")
    @ResponseBody
    public String getUserById(@PathVariable int id){
        User user = userService.getUser(id);
        return JSON.toJSONString(user);
    }
}
